<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="roleVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 数据表格区 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="item in scope.row.children"
              :key="item.id"
              class="bdbottom vcenter"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级and三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(itemSon, Sonindex) in item.children"
                  :key="itemSon.id"
                  :class="[Sonindex === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, itemSon.id)"
                      >{{ itemSon.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="itemChildren in itemSon.children"
                      :key="itemChildren.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, itemChildren.id)"
                      >{{ itemChildren.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="id"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="modifyRole(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="roleVisible"
      width="50%"
      @close="roleVisibleClosed"
    >
      <!-- 内容主体区域 -->
      <el-form :model="roleForm" ref="roleFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="modify" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="modify.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="modify.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close='setRightDialogClosed'
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys='defKeys'
        ref="treeRef"
      >
      </el-tree>
      <!-- 分配权限底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      roleList: [],
      roleForm: {
        roleName: '',
        roleDesc: '',
      },
      roleVisible: false,
      modify: {},
      editDialogVisible: false,
      setRightDialogVisible: false,
      //所有权限的数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      //默认勾选的数据
      defKeys:[],
      //当前即将分配权限角色的id
      roleId:''
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    //渲染列表
    async getRoleList() {
      const { data: response } = await this.$http.get('roles');
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.roleList = response.data;
    },
    //添加角色
    async addRole() {
      const { data: response } = await this.$http.post('roles', {
        roleName: this.roleForm.roleName,
        roleDesc: this.roleForm.roleDesc,
      });
      if (response.meta.status !== 201)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.$message({
        message: response.meta.msg,
        type: 'success',
        center: true,
      });
      this.roleVisible = false;
      this.getRoleList();
    },
    roleVisibleClosed() {
      this.$refs.roleFormRef.resetFields();
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //得到角色
    async modifyRole(id) {
      const { data: response } = await this.$http.get('roles/' + id);
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.modify = response.data;
      this.editDialogVisible = true;
    },
    //确认保存编辑后的角色
    async editUserInfo() {
      const { data: response } = await this.$http.put(
        'roles/' + this.modify.roleId,
        {
          roleDesc: this.modify.roleDesc,
          roleName: this.modify.roleName,
        }
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.editDialogVisible = false;
      this.getRoleList();
      this.$message({
        message: '修改成功',
        type: 'success',
        center: true,
      });
    },
    //删除角色
    async removeRole(id) {
      const confirmResult = await this.$confirm('确认永久删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') return;
      const { data: response } = await this.$http.delete('roles/' + id);
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.$message({
        message: response.meta.msg,
        type: 'success',
        center: true,
      });
      this.getRoleList();
    },
    //删除权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('确认删除该权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') return;
      const { data: response } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      role.children = response.data;
    },
    //分配权限
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: response } = await this.$http.get('rights/tree');
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      //把请求到的数据保存到数组中并展示对话框
      this.rightsList = response.data;
      this.getLeafKeys(role,this.defKeys)
      this.setRightDialogVisible = true;
    },
    //分配权限递归获取三级权限id
    getLeafKeys(node,arr){
      if(!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafKeys(item,arr)
      });
    },
    setRightDialogClosed(){
      this.defKeys = []
    },
    async allotRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {data:response} = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })
      if(response.meta.status !== 200) return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.$message({
          message: response.meta.msg,
          type: 'success',
          center: true,
        });
        this.getRoleList()
        this.setRightDialogVisible = false
    }
  },
};
</script>

<style scoped>
.vcenter {
  display: flex;
  align-items: center;
}

.el-tag {
  margin: 8px;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.bdtop,
.bdbottom:first-child {
  border-top: 1px solid #eee;
}
</style>